package com.zzr.zzrbackend.service.Impl;

import com.zzr.zzrbackend.config.JwtInterceptor;
import com.zzr.zzrbackend.mapper.*;
import com.zzr.zzrbackend.pojo.domain.LiveGroupChatRoom;
import com.zzr.zzrbackend.pojo.domain.MessageDetail;
import com.zzr.zzrbackend.pojo.domain.MessageGroupDetail;
import com.zzr.zzrbackend.pojo.domain.UserInfo;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.GroupNameParam;
import com.zzr.zzrbackend.pojo.dto.result.*;
import com.zzr.zzrbackend.service.MessageService;
import com.zzr.zzrbackend.util.TLSSigAPIv2;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private JwtInterceptor jwtInterceptor;
    @Resource
    private MessageDetailMapper messageDetailMapper;
    @Resource
    private LiveChatRoomMapper liveChatRoomMapper;
    @Resource
    private UnreadMessageNumMapper unreadMessageNumMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private LiveGroupChatRoomMapper liveGroupChatRoomMapper;
    @Resource
    private MessageGroupDetailMapper messageGroupDetailMapper;
    @Resource
    private UnreadGroupMessageNumMapper unreadGroupMessageNumMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private RelationMapper relationMapper;
    @Resource
    private DisabuseRecordMapper disabuseRecordMapper;


    @Override
    public CommonResult<MessageListResult> getMessageDetailList(HttpServletRequest request, Integer roomId) {

        Integer userId = jwtInterceptor.getUserId(request);
        if (userId == null) {
            return CommonResult.fail_login();
        }
        List<MessageDetail> messageDetails = messageDetailMapper.selectAllByRoomId(roomId);
        //判断用户在此房间是否有权限
        Integer jurisdiction = liveChatRoomMapper.getJurisdictionByUserIdAndRoomId(userId, roomId);
        if (jurisdiction == null) {
            return CommonResult.userAuthError("用户没有此房间的权限");
        }
        //初始化返回体
        List<MessageResult> messageResultList = new ArrayList<>();
        MessageListResult messageListResult = new MessageListResult();
        for (MessageDetail temp : messageDetails) {
            MessageResult messageResult = new MessageResult();
            messageResult.setToUserId(temp.getToUser());
            messageResult.setFromUserId(temp.getFromUser());
            messageResult.setMessage(temp.getMessage());
            messageResult.setTime(temp.getTime());
            messageResultList.add(messageResult);
        }
        messageListResult.setMessageResultList(messageResultList);
        return CommonResult.success(messageListResult);
    }

    @Override
    public CommonResult<MessageNumListResult> getMessageListNumList(HttpServletRequest request) {

        Integer userId = jwtInterceptor.getUserId(request);
        if (userId == null) {
            return CommonResult.fail_login();
        }
        //初始化返回体
        int sum = 0;
        MessageNumListResult messageNumListResult = new MessageNumListResult();
        List<MessageNumResult> messageNumResults = new ArrayList<>();

        //对单聊信息进行处理
        List<Integer> rooms = liveChatRoomMapper.getAllRoomByUserId(userId);
        for (Integer room : rooms) {
            MessageNumResult messageNumResult = new MessageNumResult();
            Integer count = unreadMessageNumMapper.selectCount(room, userId);
            if (count != null) {
                messageNumResult.setNum(count);
                sum += count;
            } else {
                messageNumResult.setNum(0);
            }
            Integer recipient = liveChatRoomMapper.getRecipientIdByRoomId(room);
            Integer initiator = liveChatRoomMapper.getInitiatorIdByRoomId(room);
            UserInfo initiatorInfo = userInfoMapper.selectByPrimaryKey(initiator);
            UserInfo recipientInfo = userInfoMapper.selectByPrimaryKey(recipient);
            if (Objects.equals(recipient, userId) && initiatorInfo != null) {
                messageNumResult.setName(userMapper.selectUserNameById(initiator));
                String picUrl = userInfoMapper.selectByPrimaryKey(initiator).getHeadPicUrl();
                if (picUrl == null) picUrl = "http://hbws.file.yuleng.top/image/default.jpeg";
                messageNumResult.setHeadPicUrl(picUrl);
            } else if (recipientInfo != null) {
                messageNumResult.setName(userMapper.selectUserNameById(recipient));
                String picUrl = userInfoMapper.selectByPrimaryKey(recipient).getHeadPicUrl();
                if (picUrl == null) picUrl = "http://hbws.file.yuleng.top/image/default.jpeg";
                messageNumResult.setHeadPicUrl(picUrl);
            }
            MessageDetail messageDetail;
            try {
                messageDetail = messageDetailMapper.selectLatestByRoomId(room);
            } catch (Exception e) {
                continue;
            }
            if (messageDetail == null) continue;
            messageNumResult.setLatestMessage(messageDetail.getMessage());
            messageNumResult.setTime(messageDetail.getTime());
            messageNumResult.setRoomId(room);
            messageNumResult.setType(1);
            messageNumResults.add(messageNumResult);
        }

        //对群聊信息处理
        List<LiveGroupChatRoom> liveGroupChatRooms = liveGroupChatRoomMapper.selectAllByUserId(userId);
        for (LiveGroupChatRoom room : liveGroupChatRooms) {
            MessageNumResult messageNumResult = new MessageNumResult();
            Integer count = unreadGroupMessageNumMapper.selectCount(room.getId(), userId);
            messageNumResult.setRoomId(room.getId());
            if (count != null) {
                messageNumResult.setNum(count);
                sum += count;
            } else {
                messageNumResult.setNum(0);
            }
            messageNumResult.setName(room.getName());
            //兼容老版本 未来可删除
            if (messageNumResult.getName() == null) {
                messageNumResult.setName("id为" + room.getDisabuseId() + "的老版本群聊");
            }
            messageNumResult.setHeadPicUrl("http://hbws.file.yuleng.top/image/qun.png");
            messageNumResult.setType(2);
            MessageGroupDetail messageGroupDetail;
            try {
                messageGroupDetail = messageGroupDetailMapper.selectLatestByRoomId(room.getId());
            } catch (Exception e) {
                continue;
            }
            if (messageGroupDetail == null) continue;
            messageNumResult.setLatestMessage(messageGroupDetail.getMessage());
            messageNumResult.setTime(messageGroupDetail.getTime());
            messageNumResults.add(messageNumResult);
        }
        //按时间排序
        messageNumResults.sort((o1, o2) -> (int) (o2.getTime() - o1.getTime()));
        messageNumListResult.setMessageNumList(messageNumResults);
        messageNumListResult.setTotal(sum);
        return CommonResult.success(messageNumListResult);
    }


    @Override
    public CommonResult<NoData> setMessageRead(HttpServletRequest request, Integer roomId, Integer type) {

        Integer userId = jwtInterceptor.getUserId(request);
        if (userId == null) {
            return CommonResult.fail_login();
        }
        try {
            if (type == 1) {
                unreadMessageNumMapper.isRead(roomId, userId);
            } else if (type == 2) {
                unreadGroupMessageNumMapper.isRead(roomId, userId);
            } else {
                return CommonResult.fail();
            }
        } catch (Exception e) {
            if ("null".equals(e.getMessage())) return CommonResult.fail("用户未有未读消息");
            return CommonResult.fail("内部错误，可能是该用户未有未读消息");
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<RoomMemberListResult> getRoomMembers(HttpServletRequest request, Integer roomId, Integer type) {
        Integer userId = jwtInterceptor.getUserId(request);
        if (userId == null) {
            return CommonResult.fail_login();
        }
        //初始化返回体
        RoomMemberListResult result = new RoomMemberListResult();
        List<RoomMemberResult> list = new ArrayList<>();

        if (type == 1) {
            //单聊处理
            RoomMemberResult recipientResult = new RoomMemberResult();
            RoomMemberResult initiatorResult = new RoomMemberResult();
            Integer initiator = liveChatRoomMapper.getInitiatorIdByRoomId(roomId);
            Integer recipient = liveChatRoomMapper.getRecipientIdByRoomId(roomId);
            String initiatorName = userMapper.selectUserNameById(initiator);
            String recipientName = userMapper.selectUserNameById(recipient);
            recipientResult.setId(recipient);
            recipientResult.setUserName(recipientName);
            initiatorResult.setId(initiator);
            initiatorResult.setUserName(initiatorName);
            String picUrl1 = userInfoMapper.selectByPrimaryKey(recipient).getHeadPicUrl();
            recipientResult.setHeadPicUrl(picUrl1);
            String picUrl2 = userInfoMapper.selectByPrimaryKey(initiator).getHeadPicUrl();
            initiatorResult.setHeadPicUrl(picUrl2);
            list.add(initiatorResult);
            list.add(recipientResult);
        } else if (type == 2) {
            //对群聊处理
            LiveGroupChatRoom liveGroupChatRoom = liveGroupChatRoomMapper.selectById(roomId);
            if (liveGroupChatRoom.getChildId() != null) {
                //小孩
                RoomMemberResult roomMemberResult = new RoomMemberResult();
                roomMemberResult.setUserName(userMapper.selectUserNameById(liveGroupChatRoom.getChildId()));
                roomMemberResult.setId(liveGroupChatRoom.getChildId());
                String picUrl = userInfoMapper.selectByPrimaryKey(liveGroupChatRoom.getChildId()).getHeadPicUrl();
                if (picUrl == null) picUrl = "http://hbws.file.yuleng.top/image/default.jpeg";
                roomMemberResult.setHeadPicUrl(picUrl);
                list.add(roomMemberResult);
            }
            if (liveGroupChatRoom.getParentId() != null) {
                //家长
                RoomMemberResult roomMemberResult = new RoomMemberResult();
                roomMemberResult.setUserName(userMapper.selectUserNameById(liveGroupChatRoom.getParentId()));
                roomMemberResult.setId(liveGroupChatRoom.getParentId());
                String picUrl = userInfoMapper.selectByPrimaryKey(liveGroupChatRoom.getParentId()).getHeadPicUrl();
                if (picUrl == null) picUrl = "http://hbws.file.yuleng.top/image/default.jpeg";
                roomMemberResult.setHeadPicUrl(picUrl);
                list.add(roomMemberResult);
            }
            if (liveGroupChatRoom.getVolunteerId() != null) {
                //志愿者
                RoomMemberResult roomMemberResult = new RoomMemberResult();
                roomMemberResult.setUserName(userMapper.selectUserNameById(liveGroupChatRoom.getVolunteerId()));
                roomMemberResult.setId(liveGroupChatRoom.getVolunteerId());
                String picUrl = userInfoMapper.selectByPrimaryKey(liveGroupChatRoom.getVolunteerId()).getHeadPicUrl();
                if (picUrl == null) picUrl = "http://hbws.file.yuleng.top/image/default.jpeg";
                roomMemberResult.setHeadPicUrl(picUrl);
                list.add(roomMemberResult);
            }
        } else {
            CommonResult.fail();
        }
        result.setRoomMembers(list);

        return CommonResult.success(result);
    }

    @Override
    public CommonResult<UserSigResult> getUserSig(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        UserSigResult userSigResult = new UserSigResult();
        userSigResult.setUserSig(TLSSigAPIv2.genUserSig(String.valueOf(claims.get("id"))));
        return CommonResult.success(userSigResult);
    }

    @Override
    public CommonResult<MessageGroupResultList> getMessageGroupDetailList(HttpServletRequest request, Integer roomId) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        if (userId == null) {
            return CommonResult.fail_login();
        }
        List<MessageGroupDetail> messageGroupDetails = messageGroupDetailMapper.selectAllByRoomId(roomId);
        //判断用户在此房间是否有权限
        Integer jurisdiction = liveGroupChatRoomMapper.getJurisdictionByUserIdAndRoomId(userId, roomId);
        if (jurisdiction == null) {
            return CommonResult.userAuthError("用户没有此房间的权限");
        }
        //初始化返回体
        List<MessageGroupResult> messageResultList = new ArrayList<>();
        MessageGroupResultList messageGroupResultList = new MessageGroupResultList();
        for (MessageGroupDetail temp : messageGroupDetails) {
            MessageGroupResult messageGroupResult = new MessageGroupResult();
            messageGroupResult.setFromUserId(temp.getFromUser());
            messageGroupResult.setMessage(temp.getMessage());
            messageGroupResult.setTime(temp.getTime());
            messageResultList.add(messageGroupResult);
        }
        messageGroupResultList.setMessageGroupResultList(messageResultList);
        return CommonResult.success(messageGroupResultList);
    }

    @Override
    public CommonResult<NoData> setGroupName(HttpServletRequest request, GroupNameParam groupNameParam) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        if (userId == null) {
            return CommonResult.fail_login();
        }
        //判断用户在此房间是否有权限
        Integer jurisdiction = liveGroupChatRoomMapper.getJurisdictionByUserIdAndRoomId(userId,
                groupNameParam.getRoomId());
        if (jurisdiction == null) {
            return CommonResult.userAuthError("用户没有此房间的权限");
        }
        liveGroupChatRoomMapper.setGroupName(groupNameParam.getRoomId(), groupNameParam.getGroupName());
        return CommonResult.success();
    }

    @Override
    public CommonResult<GroupDetailResult> getGroup(HttpServletRequest request, Integer roomId) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        if (userId == null) {
            return CommonResult.fail_login();
        }
        //判断用户在此房间是否有权限
        Integer jurisdiction = liveGroupChatRoomMapper.getJurisdictionByUserIdAndRoomId(userId, roomId);
        if (jurisdiction == null) {
            return CommonResult.userAuthError("用户没有此房间的权限");
        }
        LiveGroupChatRoom liveGroupChatRoom = liveGroupChatRoomMapper.selectById(roomId);
        List<GroupPersonDetailResult> groupPersonDetailResults = new ArrayList<>();
        if (liveGroupChatRoom.getVolunteerId() != null) {
            groupPersonDetailResults.add(setPerson(liveGroupChatRoom.getVolunteerId()));
        }
        if (liveGroupChatRoom.getParentId() != null) {
            groupPersonDetailResults.add(setPerson(liveGroupChatRoom.getParentId()));
        }
        if (liveGroupChatRoom.getChildId() != null) {
            groupPersonDetailResults.add(setPerson(liveGroupChatRoom.getChildId()));
        }
        GroupDetailResult groupDetailResult = new GroupDetailResult();
        groupDetailResult.setGroupPersonList(groupPersonDetailResults);
        groupDetailResult.setGroupName(liveGroupChatRoom.getName());
        return CommonResult.success(groupDetailResult);
    }

    @Override
    public CommonResult<SingleListResult> getSingleList(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        Integer permission = (Integer) claims.get("permission");
        SingleListResult singleListResult = new SingleListResult();
        List<GroupPersonDetailResult> list = new ArrayList<>();
        if (permission == 1) {
            //小孩
            //加入家长信息
            Integer parentId = relationMapper.selectParentIdByChildId(userId);
            GroupPersonDetailResult parentInfo = new GroupPersonDetailResult();
            UserInfo parentUserInfo = userInfoMapper.selectByPrimaryKey(parentId);
            parentInfo.setId(parentUserInfo.getUserId());
            parentInfo.setName(parentUserInfo.getUserName());
            parentInfo.setPicUrl(parentUserInfo.getHeadPicUrl());
            list.add(parentInfo);
            //加入志愿者信息
            List<Integer> volunteerList = disabuseRecordMapper.selectVolunteerIdByChildId(userId);
            setInfo(list, volunteerList);
            singleListResult.setSingleList(list);
        } else if (permission == 2) {
            //家长
            //加入小孩信息
            List<Integer> childIdList = relationMapper.selectChildIdByParentId(userId);
            setInfo(list, childIdList);
            //加入志愿者信息
            for (Integer childId : childIdList) {
                List<Integer> volunteerList = disabuseRecordMapper.selectVolunteerIdByChildId(childId);
                setInfo(list, volunteerList);
            }
            //对list去重
            List<GroupPersonDetailResult> newList = new ArrayList<>();
            for (GroupPersonDetailResult info : list) {
                if (!newList.contains(info)) {
                    newList.add(info);
                }
            }
            singleListResult.setSingleList(newList);
        } else if (permission == 3) {
            //志愿者
            List<Integer> childIdList = disabuseRecordMapper.selectChildIdByVolunteerId(userId);
            for (Integer childId : childIdList) {
                //加入儿童信息
                GroupPersonDetailResult childInfo = new GroupPersonDetailResult();
                UserInfo childUserInfo = userInfoMapper.selectByPrimaryKey(childId);
                childInfo.setId(childUserInfo.getUserId());
                childInfo.setName(childUserInfo.getUserName());
                childInfo.setPicUrl(childUserInfo.getHeadPicUrl());
                list.add(childInfo);
                //加入家长信息
                GroupPersonDetailResult parentInfo = new GroupPersonDetailResult();
                Integer parentId = relationMapper.selectParentIdByChildId(childId);
                UserInfo parentUserInfo = userInfoMapper.selectByPrimaryKey(parentId);
                parentInfo.setId(parentUserInfo.getUserId());
                parentInfo.setName(parentUserInfo.getUserName());
                parentInfo.setPicUrl(parentUserInfo.getHeadPicUrl());
                list.add(parentInfo);
            }
            //对list去重
            List<GroupPersonDetailResult> newList = new ArrayList<>();
            for (GroupPersonDetailResult info : list) {
                if (!newList.contains(info)) {
                    newList.add(info);
                }
            }
            singleListResult.setSingleList(newList);
        } else {
            return CommonResult.fail();
        }
        return CommonResult.success(singleListResult);
    }

    @Override
    public CommonResult<RoomIdResult> setSingleChat(HttpServletRequest request, Integer toUserId) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        Integer roomId = liveChatRoomMapper.selectIdByTwoUser(userId, toUserId);
        RoomIdResult roomIdResult = new RoomIdResult();
        if (roomId != null) {
            roomIdResult.setRoomId(roomId);
            try {
                roomIdResult.setRoomName(userMapper.selectUserNameById(toUserId));
            } catch (Exception e) {
                e.printStackTrace();
                roomIdResult.setRoomName(null);
            }
        } else {
            Long time = System.currentTimeMillis() / 1000;
            liveChatRoomMapper.insertLiveChat(userId, toUserId, time);
            Integer roomInsertId = liveChatRoomMapper.selectIdByTwoUser(userId, toUserId);
            roomIdResult.setRoomId(roomInsertId);
            try {
                roomIdResult.setRoomName(userMapper.selectUserNameById(toUserId));
            } catch (Exception e) {
                e.printStackTrace();
                roomIdResult.setRoomName(null);
            }
        }
        return CommonResult.success(roomIdResult);
    }

    private void setInfo(List<GroupPersonDetailResult> list, List<Integer> idList) {
        for (Integer childId : idList) {
            GroupPersonDetailResult childInfo = new GroupPersonDetailResult();
            UserInfo childUserInfo = userInfoMapper.selectByPrimaryKey(childId);
            childInfo.setId(childUserInfo.getUserId());
            childInfo.setName(childUserInfo.getUserName());
            childInfo.setPicUrl(childUserInfo.getHeadPicUrl());
            list.add(childInfo);
        }
    }

    public GroupPersonDetailResult setPerson(Integer userId) {
        GroupPersonDetailResult groupPersonDetailResult = new GroupPersonDetailResult();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        groupPersonDetailResult.setId(userId);
        groupPersonDetailResult.setName(userInfo.getUserName());
        groupPersonDetailResult.setPicUrl(userInfo.getHeadPicUrl());
        return groupPersonDetailResult;
    }
}
